package com.ty.xiaoyu.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ty.xiaoyu.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> modelMap = new HashMap<>();
        // 获取头请求中的令牌
        String token = request.getHeader("Authorization");
        try {
            JWTUtil.verify(token);
            return true;
        } catch (SignatureVerificationException e) {
            modelMap.put("code", 202);
            modelMap.put("msg", "无效签名 =>" + e.getMessage());
        } catch (TokenExpiredException e) {
            modelMap.put("code", 202);
            modelMap.put("msg", "token过期 =>" + e.getMessage());
        } catch (AlgorithmMismatchException e) {
            modelMap.put("code", 202);
            modelMap.put("msg", "token算法不一致 =>" + e.getMessage());
        } catch (Exception e) {
            modelMap.put("code", 202);
            modelMap.put("msg", "token无效 =>" + e.getMessage());
        }
        String json = new ObjectMapper().writeValueAsString(modelMap);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

}
